const express = require('express');  
const multer = require('multer');
const sp = require('child_process');
const os = require('os');
const https = require('https');
const fs = require('fs');
const path = require('path');
const config = require('config');

// 这个robotjs一直安装不成功，算了，还是Python吧
// const robot = require("robotjs");
// const robotjs = require("robotjs/build/Release/robotjs.node");

// 获取IP并发送给服务器

const interfaces = os.networkInterfaces();  
  
// for (const name of Object.keys(interfaces)) {  
const iface = interfaces[config.get("interface_name")];  

for (const alias of iface) {  
  if (alias.family === 'IPv4' && !alias.internal) {  
    console.log(`IP Address: ${alias.address}`);
    https.get(config.get("url_base") + "/LAN_IP?ip=" + alias.address);
  }  
}  

fs.mkdirSync('imgs', {recursive: true});

// https://www.cnblogs.com/sexintercourse/p/11784349.html
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'imgs/')
    },
    filename: function (req, file, cb) {
    //   const singfileArray = file.originalname.split('.');
    //   const fileExtension = singfileArray[singfileArray.length - 1];
    // TODO: 使用原始文件名保存可能存在潜在的安全问题！
    // https://dev59.com/6VwZ5IYBdhLWcg3wVO5U
      cb(null, file.originalname);
      console.log(file);
    }
});
  
const upload = multer({
    storage: storage
});

// const upload = multer({ dest: 'uploads/' }); // 指定图片保存目录  
const app = express();  
const port = config.get("local_port");  
  
// 设置跨域访问，如果你需要的话  
app.use((req, res, next) => {  
  res.header("Access-Control-Allow-Origin", "*");  
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");  
  next();  
});  
  
// 处理POST请求，保存图片  
app.post('/', upload.single('image'), (req, res) => {  
  // req.file 是 'image' 字段的文件信息  
  // req.body 将包含文本域的数据，如果有的话  
  const fileName = req.file.filename;  
  const filePath = path.posix.format(path.parse(req.file.path));  // 要把反斜杠转换成正斜杠
  
  // 在这里你可以做更多的处理，比如将文件移动到其他目录，或者存储到数据库等  
  // 目前如果是中文输入法，不会切换到英文再输入
  sp.execFile('python', [path.join(__dirname, 'pypaste.py'), `![](${filePath})`], (error, stdout, stderr) => {
    console.log("已成功输入文件地址")
  });
  console.log(fileName, filePath);

  // 返回响应  
  res.send(`文件 ${fileName} 已保存至 ${filePath}`);  
});  
  

// 启动服务器  
app.listen(port, () => {  
  console.log(`服务器正在监听端口 ${port}`);  
});